<template>
  <div class="canvas-tool">
    <div class="add-element-handler">
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" :title="item.name" v-for="(item, index) in leftData.data"
        :key="index">
        <dd :class="{ active: currentType === item.name }">
          <i :style="{ fontSize: item.type == 'video' ? '14px' : '' }" class="handler-item appIcon-iconfont" :class="item.icon"
            v-if="item.type != 'line' && item.type != 'table'" @click="handleleft(item)"></i>
        </dd>
        <dd :class="{ active: currentType === item.name }">
          <IconConnection class="handler-item" v-if="item.type == 'line'" @click="handleleft(item)" />
        </dd>
        <dd :class="{ active: currentType === item.name }">
          <IconInsertTable class="handler-item" v-if="item.type == 'table'" @click="handleleft(item)" />
        </dd>
      </Tooltip>
      <!-- <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入公式">
        <IconFormula class="handler-item" @click="latexEditorVisible = true" />
      </Tooltip> -->
      <div class="element-draw" v-if="leftPoolVisible">
        <!-- <h2>{{ currentType }}</h2>
        <i class="close appIcon-iconfont icon-yulanguanbimoren" @click="leftPoolVisible = false; currentType = '';"></i> -->
        <!-- <keep-alive>
          
        </keep-alive> -->
        <a-tabs v-model:activeKey="activeKey" :tab-position="tabPosition" v-if="currentComponent == 'ChartPool'">
          <!-- 柱状图 -->
          <a-tab-pane key="1" class="tabpane">
            <template #tab>
              <span>
                <i v-if="activeKey !== '1'" class="tool-icon appIcon-iconfont appIcon-tubiao-zhuzhuangtu"></i>
                <span v-else class="tool_title">柱状图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="barChartList" @select="(data) => drawElement(data)"
              @insert="({ row, col }:any) => { createTableElement(row, col); tableGeneratorVisible = false }">
            </component>
          </a-tab-pane>
          <!-- 折线图 -->
          <a-tab-pane key="2" class="tabpane">
            <template #tab>
              <span>
                <i v-if="activeKey !== '2'" class="tool-icon appIcon-iconfont appIcon-tubiao-zhexiantu"></i>
                <span v-else class="tool_title">折线图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="lineChartList" @select="(data) => drawElement(data)" @insert="
              ({ row, col }:any) => {
                createTableElement(row, col);
                tableGeneratorVisible = false;
              }
            "></component>
          </a-tab-pane>
          <!-- 圆饼图 -->
          <a-tab-pane key="3" class="tabpane">
            <template #tab>
              <span>
                <i v-if="activeKey !== '3'" class="tool-icon appIcon-iconfont appIcon-24gl-chartPie"></i>
                <span v-else class="tool_title">圆饼图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="PieChart" @select="(data) => drawElement(data)" @insert="
              ({ row, col }:any) => {
                createTableElement(row, col);
                tableGeneratorVisible = false;
              }
            "></component>
          </a-tab-pane>
          <!-- 散点图 -->
          <a-tab-pane key="4" class="tabpane">
            <template #tab>
              <span>
                <i v-if="activeKey !== '4'" class="tool-icon appIcon-iconfont appIcon-sandiantu"></i>
                <span v-else class="tool_title">散点图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="ScatterDiagram" @select="(data) => drawElement(data)" @insert="
              ({ row, col }:any) => {
                createTableElement(row, col);
                tableGeneratorVisible = false;
              }
            "></component>
          </a-tab-pane>
          <!-- 雷达图 -->
          <a-tab-pane key="5" class="tabpane">
            <template #tab>
              <span>
                <i v-if="activeKey !== '5'" class="tool-icon appIcon-iconfont appIcon-radarchart"></i>
                <span v-else class="tool_title">雷达图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="RadarChart" @select="(data) => drawElement(data)" @insert="
              ({ row, col }:any) => {
                createTableElement(row, col);
                tableGeneratorVisible = false;
              }
            "></component>
          </a-tab-pane>
          <!-- 更多图 -->
          <!-- <a-tab-pane key="6">
            <template #tab>
              <span>
                <i v-if="activeKey !== '6'" class="tool-icon appIcon-iconfont icon-qita2"></i>
                <span v-else class="tool_title">更多图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="OtherFigures" @select="data => drawElement(data)"
              @insert="({ row, col }) => { createTableElement(row, col); tableGeneratorVisible = false }"></component>
          </a-tab-pane> -->
        </a-tabs>

        <a-tabs v-model:activeKey="mapKey" :tab-position="tabPosition" v-if="currentComponent == 'MapPool'">
          <!-- 2D地图 -->
          <a-tab-pane key="1" class="tabpane">
            <template #tab>
              <span>
                <i v-if="mapKey !== '1'" class="tool-icon appIcon-iconfont appIcon-ditu"></i>
                <span v-else class="tool_title">2D地图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="twmapList" @select="(data) => drawElement(data)" @insert="
              ({ row, col }:any) => {
                createTableElement(row, col);
                tableGeneratorVisible = false;
              }
            "></component>
          </a-tab-pane>
          <!-- 2D地图 -->
          <a-tab-pane key="2" class="tabpane">
            <template #tab>
              <span>
                <i v-if="mapKey !== '2'" class="tool-icon appIcon-iconfont appIcon-ditu"></i>
                <span v-else class="tool_title">3D地图</span>
              </span>
            </template>
            <component :is="currentComponent" :chartList="thmapList" @select="(data) => drawElement(data)" @insert="
              ({ row, col }:any) => {
                createTableElement(row, col);
                tableGeneratorVisible = false;
              }
            "></component>
          </a-tab-pane>
        </a-tabs>

        <component :is="currentComponent" @select="(data) => drawElement(data)" @insert="
          ({ row, col }:any) => {
            createTableElement(row, col);
            tableGeneratorVisible = false;
          }
        "></component>
      </div>
      <!-- <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入公式">
        <IconFormula class="handler-item" @click="latexEditorVisible = true" />
      </Tooltip> -->
      <!-- <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入音视频">
        <IconVideoTwo class="handler-item" @click="mediaInputVisible = true" />
      </Tooltip> -->
    </div>

    <div class="right-handler">
      <dd :class="{ active: currentType === '页面图层' }">
        <div class="handler-item" @click="handleright">
          <i class="appIcon-iconfont appIcon-tuceng"></i>
        </div>
      </dd>
      <a-popover trigger="hover" v-model:visible="scaleVisible" placement="right"
        overlayClassName="canvasToolright_handler">
        <template #content>
          <div class="flex">
            <IconMinus class="viewport-size" @click="scaleCanvas('-')" />
            <IconPlus class="viewport-size" @click="scaleCanvas('+')" />
            <!-- <IconFullScreen class="viewport-size" @click="setCanvasPercentage(90)" /> -->
          </div>
          <!-- <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="适配屏幕">
            <IconFullScreen class="handler-item viewport-size-adaptation" @click="setCanvasPercentage(90)" />
          </Tooltip> -->
        </template>
        <span class="text">{{ canvasScalePercentage }}</span>
      </a-popover>
    </div>
    <!-- <Modal v-model:visible="mediaInputVisible" :footer="null" centered :width="540" destroyOnClose>
      <MediaInput @close="mediaInputVisible = false"
        @insertVideo="src => { createVideoElement(src); mediaInputVisible = false }"
        @insertAudio="src => { createAudioElement(src); mediaInputVisible = false }" />
    </Modal> -->
    <Modal v-model:visible="latexEditorVisible" :footer="null" centered :width="880" destroyOnClose>
      <LaTeXEditor @close="latexEditorVisible = false" @update="
        (data:any) => {
          createLatexElement(data);
          latexEditorVisible = false;
        }
      " />
    </Modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, reactive, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useMainStore, useSnapshotStore } from "@/store";
import { getImageDataURL, urlToBase64 } from "@/utils/image";
import { ShapePoolItem } from "@/configs/shapes";
import { LinePoolItem } from "@/configs/lines";

import useScaleCanvas from "@/hooks/useScaleCanvas";
import useHistorySnapshot from "@/hooks/useHistorySnapshot";
import useCreateElement from "@/hooks/useCreateElement";

import ShapePool from "./ShapePool.vue";
import LinePool from "./LinePool.vue";
import ChartPool from "./ChartPool.vue";
import MapPool from "./MapPool.vue";
import TextPool from "./TextPool.vue";
import ImagePool from "./ImagePool.vue";
import VideoPool from "./VideoPool.vue";
import TableGenerator from "./TableGenerator.vue";
import CustomPool from "./CustomPool.vue";
import LayerPool from "./LayerPool.vue";
import MediaInput from "./MediaInput.vue";
import LaTeXEditor from "@/components/LaTeXEditor/index.vue";
import emitter, { EmitterEvents } from "@/utils/emitter";
import { CreateElementSelectionData } from "@/types/edit";
import { ChartType, TextType } from "@/types/slides";
// import { BAR_CHART_LIST } from '@/configs/chart'
// import { LINE_CHART_LIST } from '@/configs/chart'
import {
  twmapArrary,
  thmapArrary,
  HistogramArrary,
  LineChartArrary,
  ScatterDiagramArrary,
  PieChartArrary,
  OtherFiguresArrary,
  RadarChartArrary,
} from "@/configs/chart";

export default defineComponent({
  name: "canvas-tool",
  components: {
    ShapePool,
    LinePool,
    ChartPool,
    TableGenerator,
    MediaInput,
    LaTeXEditor,
    TextPool,
    ImagePool,
    VideoPool,
    CustomPool,
    LayerPool,
    MapPool,
  },
  setup() {
    const mainStore = useMainStore();
    const { canvasScale } = storeToRefs(mainStore);
    const tabPosition = ref("left");
    const activeKey = ref("1");
    const mapKey = ref("1");
    const barChartList = HistogramArrary; // 柱状图
    const lineChartList = LineChartArrary; // 折线图
    const ScatterDiagram = ScatterDiagramArrary; // 散点图
    const PieChart = PieChartArrary; // 饼图
    const RadarChart = RadarChartArrary; // 雷达图
    const OtherFigures = OtherFiguresArrary; // 其他
    const twmapList = twmapArrary; // 2d地图
    const thmapList = thmapArrary; // 3d地图

    let currentType = ref("ChartPool");
    let currentComponent = ref();
    let categroy = ref("");
    let leftData = reactive({
      data: [
        {
          name: "插入图表",
          type: "chart",
          icon: "appIcon-zhuzhuangtu",
          component: "ChartPool",
        },
        {
          name: "插入地图",
          type: "map",
          icon: "appIcon-ditu",
          categroy: "map",
          component: "MapPool",
        },
        {
          name: "插入文字",
          type: "text",
          icon: "appIcon-wenzi1",
          component: "TextPool",
        },
        {
          name: '插入图片',
          type: 'image',
          icon: 'appIcon-tupian4',
          component: 'ImagePool'
        },
        {
          name: "插入视频",
          type: "video",
          icon: "appIcon-tuxingzujian-yunpanshipinmoren",
          component: "VideoPool",
        },
        {
          name: "插入形状",
          type: "shape",
          icon: "appIcon-xingzhuangmoren",
          component: "ShapePool",
        },
        {
          name: "插入线条",
          type: "line",
          icon: "i-icon-connection",
          component: "LinePool",
        },

        {
          name: "插入表格",
          type: "table",
          icon: "i-icon-insert-table",
          component: "TableGenerator",
        },
        {
          name: "自定义组件",
          type: "custom",
          icon: "appIcon-zidingyizujian",
          component: "CustomPool",
        },
      ],
    });
    const canvasScalePercentage = computed(
      () => parseInt(canvasScale.value * 100 + "") + "%"
    );

    const { scaleCanvas, setCanvasPercentage } = useScaleCanvas();
    const { redo, undo } = useHistorySnapshot();

    const {
      createChartElement,
      createTableElement,
      createLatexElement,
      createVideoElement,
      createAudioElement,
    } = useCreateElement();

    const shapePoolVisible = ref(false);
    const linePoolVisible = ref(false);
    const chartPoolVisible = ref(false);
    const tableGeneratorVisible = ref(false);
    const mediaInputVisible = ref(false);
    const latexEditorVisible = ref(false);
    const scaleVisible = ref<boolean>(false);
    const imgPoolVisible = ref(false);
    const textPoolVisible = ref(false);
    const leftPoolVisible = ref(false);

    const drawElement = (data: any) => {
      if (data.text) drawText(data);
      if (data.url) drawImage(data);
      if (data.shape) drawShape(data);
      if (data.line) drawLine(data);
      if (data.chart) drawChart(data);
      if (data.table) drawImage(data);
      if (data.custom) drawCustom(data);
      if (data.videourl) drawVideo(data);
    };
    // 绘制文字范围
    interface textItem {
      text: any;
      $event: MouseEvent;
    }
    const drawText = (text: textItem) => {
      mainStore.setCreatingElement({
        type: "text",
        data: text.text,
      });
      insertElement(text.$event);
    };
    // 绘制图片
    interface imageItem {
      imageSize: number;
      url: string;
      $event: MouseEvent;
    }
    const drawImage = (url: imageItem) => {
      mainStore.setCreatingElement({
        type: "image",
        data: url.url,
        size: url.imageSize,
      });
      insertElement(url.$event);
    };

    //绘制视频
    interface videoItem {
      videourl: string;
      $event: MouseEvent;
      fileAvatar: string;
    }
    const drawVideo = (url: videoItem) => {
      mainStore.setCreatingElement({
        type: "video",
        data: url.videourl,
        fileAvatar: url.fileAvatar,
      });
      insertElement(url.$event);
      // createVideoElement(url.videourl)
      // mainStore.setDragIndex('')
    };

    // 绘制形状范围
    interface shapeItem {
      shape: ShapePoolItem;
      $event: MouseEvent;
    }
    const drawShape = (shape: shapeItem) => {
      mainStore.setCreatingElement({
        type: "shape",
        data: shape.shape,
      });
      shapePoolVisible.value = false;
      insertElement(shape.$event);
    };
    const insertElement = (e: MouseEvent) => {
      // console.log(e, '----------------------------')

      const endPageX = e.pageX;
      const endPageY = e.pageY;
      emitter.emit(EmitterEvents.INSERT_ELEMENT, {
        start: [endPageX, endPageY],
        end: [endPageX + 200, endPageY + 200],
      });
    };
    // 绘制线条路径
    interface lineItem {
      $event: MouseEvent;
      line: LinePoolItem;
    }
    const drawLine = (line: lineItem) => {
      mainStore.setCreatingElement({
        type: "line",
        data: line.line,
      });
      linePoolVisible.value = false;
      insertElement(line.$event);
    };
    //绘制图表
    interface chartItem {
      $event: MouseEvent;
      chart: any; //类型
      data: any; //图表数据
    }
    const drawChart = (chart: chartItem) => {
      mainStore.setCreatingElement({
        type: "chart",
        data: chart.chart,
        antvdata: chart.data,
      });

      insertElement(chart.$event);
      chartPoolVisible.value = false;
    };
    //绘制自定义组件
    interface customItem {
      $event: MouseEvent;
      custom: any;
    }
    const drawCustom = (custom: customItem) => {
      mainStore.setCreatingElement({
        type: "custom",
        data: custom.custom,
      });

      insertElement(custom.$event);
    };
    const handleleft = (item: any) => {
      activeKey.value = "1";
      console.log(currentType.value, item.type);

      if (currentComponent.value != item.component) {
        currentType.value = item.name;
        currentComponent.value = item.component;
        leftPoolVisible.value = true;
      } else {
        leftPoolVisible.value = false;
        currentComponent.value = "";
        currentType.value = "";
      }

      // textPoolVisible.value = !textPoolVisible.value
    };
    const handleright = () => {
      handleleft({
        name: "页面图层",
        component: "LayerPool",
      });
    };
    onMounted(() => {
      // console.log(Histogram);
      document.addEventListener("mouseup", (e: any) => {
        var _con = document.querySelector(".element-draw");
        if (_con) {
          if (!_con.contains(e.target)) {
            leftPoolVisible.value = false;
            currentType.value = "";
          }
        }
      });
    });
    return {
      scaleCanvas,
      setCanvasPercentage,
      canvasScalePercentage,
      redo,
      undo,
      shapePoolVisible,
      linePoolVisible,
      chartPoolVisible,
      textPoolVisible,
      tableGeneratorVisible,
      mediaInputVisible,
      latexEditorVisible,
      scaleVisible,
      leftPoolVisible,
      drawText,
      drawImage,
      drawVideo,
      drawShape,
      drawLine,
      drawChart,
      createChartElement,
      createTableElement,
      createLatexElement,
      createVideoElement,
      createAudioElement,
      imgPoolVisible,
      insertElement,
      handleleft,
      handleright,
      leftData,
      currentType,
      currentComponent,
      drawElement,
      drawCustom,
      tabPosition,
      activeKey,
      barChartList,
      lineChartList,
      ScatterDiagram,
      PieChart,
      OtherFigures,
      RadarChart,
      mapKey,
      categroy,
      twmapList,
      thmapList,
    };
  },
});
</script>

<style lang="scss" scoped>
.element-draw {
  width: 290px;
  background: $darkGray;
  height: 100%;
  border-radius: 0;
  position: absolute;
  left: 54px;
  top: 0;
  z-index: 9999;

  .close {
    position: absolute;
    display: block;
    right: 10px;
    top: 5px;
    font-size: 14px;
    color: #fff;
    cursor: pointer;
    transition: 0.5s all ease;
    opacity: 0.8;
    padding: 20px;

    &:hover {
      opacity: 1;
    }
  }

  h2 {
    font-size: 18px;
    color: #ffffff;
    letter-spacing: 0;
    line-height: 60px;
    font-weight: 400;
    text-align: center;
  }

  ul {
    overflow: hidden;
    overflow-y: overlay;
    height: 100%;
    margin-top: 20px;
  }
}

::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  background-color: $leftbg;
}

::-webkit-scrollbar-thumb {
  background-color: transparent;
}

.canvas-tool {
  position: relative;
  background-color: #fff;
  font-size: 13px;
  user-select: none;
}

.active {
  .handler-item {
    color: $defaultIconColor;
  }
}

.handler-item {
  font-size: 15px;
  color: $defaultIconColor;
  height: 60px;
  cursor: pointer;
  display: block;
  text-align: center;
  padding-top: 20px;
  transition: 0.5s all ease;

  &.disable {
    opacity: 0.5;
  }

  &:hover {
    color: $hoverIconColor;
  }
}

.right-handler {
  width: 100%;
  text-align: center;
  color: #fff;
  margin-bottom: 50px;

  .appIcon-iconfont {
    font-size: 24px;
  }

  .text {
    cursor: pointer;
    display: block;
    margin: 10px 0;
  }
}

.flex {
  display: flex;

  .viewport-size {
    padding: 0 20px;
    cursor: pointer;
  }
}

.tool_title {
  font-size: 10px;
  width: 36px;
}
</style>
<style lang="scss">
.canvasToolright_handler {
  padding-left: 25px;
  // transform: translateX(35px);
  // margin-left: 35px;

  .ant-popover-inner {
    background-color: #252736;

    .ant-popover-inner-content {
      color: #fff;

      .viewport-size {
        width: 28px;
        height: 28px;
        margin: 0 12px;
        background: #424755;
        padding: 0;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover {
          background-color: #5c5d71;
        }
      }
    }
  }
}

.tool-icon {
  font-size: 17px;

  &:hover {
    color: white;
  }
}

.ant-tabs {
  color: $defaultIconColor;
}

.ant-tabs-left>.ant-tabs-nav .ant-tabs-tab,
.ant-tabs-right>.ant-tabs-nav .ant-tabs-tab,
.ant-tabs-left>div>.ant-tabs-nav .ant-tabs-tab,
.ant-tabs-right>div>.ant-tabs-nav .ant-tabs-tab {
  padding: 8px 10px;
  text-align: center;
}

.ant-tabs-tab {
  margin: 16px auto 0 auto !important;
}

.ant-tabs-tab:hover {
  color: white;
}

.tabpane {
  background: $lightGray;
}

.ant-tabs-left>.ant-tabs-content-holder>.ant-tabs-content>.ant-tabs-tabpane,
.ant-tabs-left>div>.ant-tabs-content-holder>.ant-tabs-content>.ant-tabs-tabpane {
  padding-left: 0;
}

.ant-tabs-left>.ant-tabs-content-holder {
  border: none;
}

.ant-tabs-tab.ant-tabs-tab-active {
  background: #27292d;
}
</style>
